# -*- coding:utf-8 -*-

from tornado import web, gen
import os

from appcommon.framework import APIRequestHandler
from appcommon import checktool
from common import decorator
from common import utiltool
import models as paym
import tools as payt
import user.models as userm
import user.tools as usert
from couch import models as couchm
from common import timetool
from xml.etree import ElementTree
import settings


class GetOrderHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        order_type = self.get_argument('order_type', 'vip1')
        order_info = yield paym.get_order_with_phone(phone, order_type)
        for item in order_info:
            yield paym.del_old_order(item['out_trade_no'])
        from_phone = yield userm.get_from_phone(phone)
        price = yield paym.get_order_price(order_type)
        is_youhui = 0
        # 符合优惠条件，优惠三块
        if order_type in ['vip1', 'vip4']:
            total_fee = price['youhui_price'] if from_phone else price['price']
            is_youhui = 1 if from_phone else 0
        else:
            total_fee = price['price']
        create_time = timetool.get_timestamp()
        out_trade_no = paym.create_out_trade_no(phone)
        order_info = dict(
            phone=phone,
            total_fee=total_fee,
            create_time=create_time,
            out_trade_no=out_trade_no,
            is_youhui=is_youhui,
            order_type=order_type
        )
        res = {"code": "0", "info": order_info}
        yield paym.insert_order_2_mysql(order_info, from_phone)
        utiltool.response_write(self, res)


class WxPayHandler(APIRequestHandler):
    """微信支付，获取微信预付单ID"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        out_trade_no = self.get_argument('out_trade_no', '')
        pay_type = self.get_argument('pay_type', 'app')
        order_info = yield paym.get_order_with_out(out_trade_no)
        #
        if order_info:
            res = paym.wx_get_pre_order_id(order_info['phone'], out_trade_no, str(int(order_info['total_fee']*100)), pay_type, '', order_info['body'])
            # res = paym.wx_get_pre_order_id(order_info['phone'], out_trade_no, '1', pay_type, '', order_info['body'])
            print res
            utiltool.response_write(self, res)
        else:
            utiltool.response_write(self, {"code": "1", "msg": u"无效的订单号"})


class WxJsPayHandler(APIRequestHandler):
    """微信js支付"""
    @checktool.check_sign
    @payt.check_id_code
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        code = self.get_argument('code', '')
        from_phone = self.get_argument('share_phone', '')
        order_type = self.get_argument('order_type', 'vip1')
        order_info = yield paym.get_order_with_phone(phone, order_type)
        for item in order_info:
            yield paym.del_old_order(item['out_trade_no'])
        price = yield paym.get_order_price(order_type)
        # 价格
        if order_type == 'vip1':
            total_fee = price['price']
        elif order_type == 'vip4':
            total_fee = price['price']
        else:
            total_fee = price['price']
        create_time = timetool.get_timestamp()
        out_trade_no = paym.create_out_trade_no(phone)
        order_info = dict(
            phone=phone,
            total_fee=total_fee,
            create_time=create_time,
            out_trade_no=out_trade_no,
            order_type=order_type
        )
        yield paym.insert_order_2_mysql(order_info, from_phone)
        pay_type = 'gzh'
        openid = yield paym.get_openid_with_code(code)
        #
        if order_info['order_type'] == 'vip1':
            body = u'开通科目一VIP'
        elif order_info['order_type'] == 'vip4':
            body = u'开通科目四VIP'
        else:
            body = u'开通报名通'
        res = paym.wx_get_pre_order_id(order_info['phone'], out_trade_no, str(int(order_info['total_fee']*100)), pay_type, openid, body)
        # res = paym.wx_get_pre_order_id(order_info['phone'], out_trade_no, '1', pay_type, openid, body)
        print res
        utiltool.response_write(self, res)


class WxNotifyHandler(APIRequestHandler):
    """微信支付，回调"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        remote_ip = utiltool.get_remote_ip(self)
        root = ElementTree.fromstring(str(self.request.body))
        return_code = root.find('return_code')
        result_code = root.find('result_code')
        # 通信是否成功
        if return_code.text != 'SUCCESS':
            ret_msg = '''<xml><return_code><![CDATA[Fail]]></return_code>
                                            <return_msg><![CDATA[通信失败]]></return_msg></xml>'''
        else:
            resultdict = {}
            for child in root:
                resultdict[child.tag] = child.text
            print resultdict
            sign = resultdict['sign']
            del resultdict['sign']
            signkey = ''
            for s in ['gzh', 'app']:
                if resultdict['appid'] == settings.PAY_TYPE[s]['appid']:
                    signkey = settings.PAY_TYPE[s]['signkey']
                    break
            sci_sign = paym.creatsig_md5(resultdict, signkey)
            # 如果签名验证通过
            if sci_sign == sign:
                if result_code.text == 'SUCCESS':
                    yield payt.deal_wx_pay_success_order(resultdict)
                    yield paym.update_order_status(resultdict['out_trade_no'], 2, 'wechat')
                else:
                    yield paym.update_order_status(resultdict['out_trade_no'], 3, 'wechat')
                yield paym.save_wechat_pay_log(resultdict)
                ret_msg = '''<xml><return_code><![CDATA[SUCCESS]]></return_code>
                                <return_msg><![CDATA[OK]]></return_msg></xml>'''
            else:
                ret_msg = '''<xml><return_code><![CDATA[Fail]]></return_code>
                                            <return_msg><![CDATA[签名验证失败]]></return_msg></xml>'''
        self.write(ret_msg)


class AliPayHandler(APIRequestHandler):
    """支付宝支付，获取支付宝预付单ID"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        out_trade_no = self.get_argument('out_trade_no', '')
        order_info = yield paym.get_order_with_out(out_trade_no)
        #
        if order_info:
            # res = paym.ali_get_pre_order_id(order_info['phone'], out_trade_no, '0.01', order_info['body'])
            res = paym.ali_get_pre_order_id(order_info['phone'], out_trade_no, order_info['total_fee'], order_info['body'])
            utiltool.response_write(self, res)
        else:
            utiltool.response_write(self, {"code": "1", "msg": u"无效的订单号"})


class AliNotifyHandler(APIRequestHandler):
    """支付宝支付，回调"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        resultdict = self.request.arguments
        ali_auth = yield paym.check_ali_notify_auth(resultdict)
        if ali_auth:
            if resultdict['trade_status'][0] == 'TRADE_SUCCESS':
                yield payt.deal_ali_pay_success_order(resultdict)
                yield paym.update_order_status(resultdict['out_trade_no'][0], 2, 'ali')
                ret_msg = 'success'
            else:
                yield paym.update_order_status(resultdict['out_trade_no'][0], 3, 'ali')
                ret_msg = 'fail'
            yield paym.save_ali_pay_log(resultdict)
        else:
            ret_msg = 'fail'
        self.write(ret_msg)


class SendMsgHandler(APIRequestHandler):
    """发送短信验证码"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        id_code = paym.create_id_code()
        usert.send_id_code(id_code, phone)
        yield paym.save_id_code_to_mysql(phone, id_code)
        utiltool.response_write(self, {'code': '0'})
